<?php

namespace adminmatrix\server\app\server;

use think\response\Json;

class JsonService
{

    /**
     * @param ...$args
     * @return Json
     */
    public static function success(...$args) : Json
    {
        return self::strTo(...$args);
    }


    public static function yes(int $code = 1 ,  string  $message = "", array $data  = [] , int $show = 1, int $httpCode =200  , array $feedback = ["func"=>"notifySuccess"]) : Json
    {
        return self::result($code , $message , $data , $httpCode , $show , $feedback);
    }

    public static function throw(string $msg = 'fail', array $data = [], int $code = 0, int $show = 1): Json
    {
        $data = compact('code', 'show', 'msg', 'data');
        $response = Response::create($data, 'json', 200);
        throw new HttpResponseException($response);
    }

    public static function fail(...$args) :     Json
    {
        return self::strTo(...$args);
    }

    private static function result(
        int $code ,
        string $message ,
        mixed $data ,
        int $httpCode,
        int $show,
        array $feedback
    ) : Json
    {
        $data = compact('code' , 'message' , 'data' , 'show' , 'feedback');
        return json($data , $httpCode);
    }


    private static function strTo(...$args) : Json
    {
        $trace = debug_backtrace();
        $caller = $trace[1]['function'];
        $code = match ($caller){
            "success"   =>  1,
            "fail"      =>  0,
        };
        $defaultArray = [
            'code'      =>  $code,
            "message"   =>  '',
            "data"      =>  [],
            "httpCode"  =>  200,
            'show'      =>  1,
            "feedback"  =>  [
                "func"  =>  'msg',
            ]
        ];
        foreach ($args as $arg) {
            if (empty($args['data']) && is_array($arg)) {
                $defaultArray['data'] = $arg;
            } elseif (is_string($arg)) {
                $defaultArray['message'] = $arg;
            } elseif (is_int($arg)) {
                if ($arg !== 1) {
                    $defaultArray['httpCode'] = $arg;
                } else {
                    $defaultArray['code'] = $arg;
                }
            } else {
                $defaultArray['result'] = $arg;
            }
        }


        return self::result(
            $defaultArray["code"],
            $defaultArray["message"],
            $defaultArray["data"],
            $defaultArray["httpCode"],
            $defaultArray['show'],
            $defaultArray['feedback'],
        );
    }
}